package com.social.action;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.CoreConstants;
import com.base.action.CoreController;
import com.base.dao.model.Grid;
import com.base.dao.model.Ret;
import com.base.dialect.PaginationSupport;
import com.base.service.BFileService;
import com.base.util.DFA;
import com.base.util.JSONUtils;
import com.base.util.StringUtil;
import com.base.web.annotation.LoginFilter;
import com.social.dao.model.ForumAd;
import com.social.dao.model.ForumAdExample;
import com.social.dao.model.Label;
import com.social.dao.model.LabelExample;
import com.social.dao.model.Topic;
import com.social.dao.model.TopicCategory;
import com.social.dao.model.TopicCategoryExample;
import com.social.dao.model.TopicComment;
import com.social.daoEx.model.LabelEx;
import com.social.daoEx.model.TopicCommentEx;
import com.social.daoEx.model.TopicEx;
import com.social.service.ForumAdService;
import com.social.service.LabelService;
import com.social.service.TopicCategoryService;
import com.social.service.TopicCommentService;
import com.social.service.TopicService;


@RequestMapping("social")
@Controller
@LoginFilter
public class SocialController extends CoreController {
	@Autowired
	private TopicCommentService commentService;
	@Autowired
	private TopicService topicService;
	@Autowired
	private TopicCategoryService categoryService;
	@Autowired
	private BFileService fileService;
	@Autowired
	private LabelService labelService;
	@Autowired
	private ForumAdService adService;
	
	@RequestMapping("circleList")
	@ResponseBody
	public String circleList(String account,Integer page, Integer rows) {
		PaginationSupport.byPage(page, rows);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("account", account);
		map.put("topicId", "0");
		List<TopicCommentEx> list = commentService.selectWebCircleList(map);
		return JSONUtils.serialize(new Grid(PaginationSupport.getContext().getTotalCount(), list));
	}
	
	@RequestMapping("/circleDel")
	@ResponseBody
	public String circleDel(String id)throws Exception{
		String[] ids = id.split(",");
		for (String c : ids) {
			commentService.deleteByPrimaryKey(c);
		}
		return JSONUtils.serialize(new Ret(0));
	}

	@RequestMapping("topicList")
	@ResponseBody
	public String topicList(Integer state,String cateCode,String account,String label,Integer page, Integer rows) {
		PaginationSupport.byPage(page, rows);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("account", account);
		map.put("label", label);
		map.put("state", state);
		map.put("cateCode", cateCode);
		List<TopicEx> list = topicService.selectWebTopicList(map);
		return JSONUtils.serialize(new Grid(PaginationSupport.getContext().getTotalCount(), list));
	}
	
	@RequestMapping("/topicUpdate")
	@ResponseBody
	public String topicUpdate(Integer state,String id)throws Exception{
		String[] ids = id.split(",");
		Topic record = new Topic();
		for (String c : ids) {
			record.setId(c);
			record.setState(state);
			topicService.updateByPrimaryKeySelective(record);
		}
		return JSONUtils.serialize(new Ret(0));
	}
	
	@RequestMapping("/topicTop")
	@ResponseBody
	public String topicTop(Integer isTop,String id)throws Exception{
		Topic record = new Topic();
		record.setId(id);
		record.setIsTop(isTop);
		topicService.updateByPrimaryKeySelective(record);
		return JSONUtils.serialize(new Ret(0));
	}
	
	@RequestMapping("/topicHot")
	@ResponseBody
	public String topicHot(Integer isHot,String id)throws Exception{
		Topic record = new Topic();
		record.setId(id);
		record.setIsHot(isHot);
		topicService.updateByPrimaryKeySelective(record);
		return JSONUtils.serialize(new Ret(0));
	}
	
	@RequestMapping("/cateTree")
	@ResponseBody 
	public String cateTree(String combotree,Integer level) throws Exception{
		TopicCategoryExample example = new TopicCategoryExample();
		example.setOrderByClause("sort_order desc");
		if(level!=null){
			example.createCriteria().andLevelEqualTo(level);
		}
		List<TopicCategory> list = categoryService.selectByExample(example);
		if(StringUtils.isNotBlank(combotree)){
			for (TopicCategory cate : list) {
				cate.setId(cate.getCode());
			}
		}else{
			TopicCategory cate = new TopicCategory();
			cate.setId("0");
			cate.setCode("0");
			cate.setTitle("分类");
			cate.setLevel(0);
			cate.setParentCode("0");
			list.add(0, cate);
		}
		return JSONUtils.serialize(list);
	}
	
	@RequestMapping(value="/cateSave",method=RequestMethod.POST)
	@ResponseBody
	public String cateSave(TopicCategory cate)throws Exception{
		if(StringUtil.isEmpty(cate.getId())){
			cate.setCreateTime(new Date());
			if(cate.getLevel()!=1){
				cate.setCode(cate.getParentCode()+cate.getCode());
			}
			categoryService.insert(cate);
		}else{
			categoryService.updateByPrimaryKeySelective(cate);
		}
		return JSONUtils.serialize(new Ret(0));
	}
	
	@RequestMapping(value="/findCateById")
	@ResponseBody
	public String findById(String id)throws Exception{
		TopicCategory category = categoryService.selectByPrimaryKey(id);
		return JSONUtils.serialize(category);
	}
	
	@RequestMapping("/cateDel")
	@ResponseBody
	public String del(String code)throws Exception{
		String[] ids = code.split(",");
		for (String c : ids) {
			TopicCategoryExample example = new TopicCategoryExample();
			example.createCriteria().andCodeLike(c+"%");
			categoryService.deleteByExample(example);
		}
		return JSONUtils.serialize(new Ret(0));
	}
	
	
	@RequestMapping("/checkCateCode")
	@ResponseBody
	public String checkCode(String parent,String value)throws Exception{
		if(!"0".equals(parent)){
			value = parent+value;
		}
		TopicCategoryExample example = new TopicCategoryExample();
		example.createCriteria().andCodeEqualTo(value);
		int count = categoryService.countByExample(example);
		if(count!=0){
			return JSONUtils.serialize(new Ret(1));
		}
		return JSONUtils.serialize(new Ret(0));
	}
	
	@RequestMapping("commentList")
	@ResponseBody
	public String commentList(Integer state,String topicId,String account,Integer page, Integer rows) {
		PaginationSupport.byPage(page, rows);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("account", account);
		map.put("state", state);
		map.put("topicId", topicId);
		List<TopicCommentEx> list = commentService.selectWebCommentList(map);
		return JSONUtils.serialize(new Grid(PaginationSupport.getContext().getTotalCount(), list));
	}
	
	@RequestMapping("/commentUpdate")
	@ResponseBody
	public String commentUpdate(Integer state,String id)throws Exception{
		String[] ids = id.split(",");
		TopicComment record = new TopicComment();
		for (String c : ids) {
			record.setId(c);
			record.setState(state);
			commentService.updateByPrimaryKeySelective(record);
		}
		return JSONUtils.serialize(new Ret(0));
	}
	
	@RequestMapping("/loadSensitiveWords")
	@ResponseBody
	public String loadSensitiveWords()throws Exception{
		String txt = "";
		String filePath = CoreConstants.getProperty("social.sensitive_word_filepath");
		if(StringUtils.isNotBlank(filePath)){
			File file = new File(filePath);
			if(file.isFile() && file.exists()){
				try {
					InputStreamReader read = new InputStreamReader(new FileInputStream(file),"gbk");
					BufferedReader br = new BufferedReader(read);
					String lineTxt = null;
					while((lineTxt = br.readLine()) != null){
						txt+=lineTxt;
					}	
					read.close();
				} catch (Exception e) {
					e.printStackTrace();
					return JSONUtils.serialize(new Ret(1,"敏感词加载失败"));
				}
			}
		}
		return JSONUtils.serialize(new Ret(0,txt));
	}
	
	@RequestMapping("/saveSensitiveWords")
	@ResponseBody
	public String saveSensitiveWords(String content)throws Exception{
		String filePath = CoreConstants.getProperty("social.sensitive_word_filepath");
		if(StringUtils.isNotBlank(filePath)){
			File file = new File(filePath);
			if(file.isFile() && file.exists()){
				try {
					OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "gbk");
					BufferedWriter bw = new BufferedWriter(writer);
					bw.write(content);
					bw.close();
					if(DFA.keyMap != null)
						DFA.reloadData();
				} catch (Exception e) {
					e.printStackTrace();
					return JSONUtils.serialize(new Ret(1,"敏感词保存失败"));
				}
			}
		}
		return JSONUtils.serialize(new Ret(0));
	}
	
	@RequestMapping("labelList")
	@ResponseBody
	public String labelList(String cateCode,String title,Integer page, Integer rows) {
		PaginationSupport.byPage(page, rows);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("title", title);
		map.put("cateCode", cateCode);
		List<LabelEx> list = labelService.selectWebLabelList(map);
		return JSONUtils.serialize(new Grid(PaginationSupport.getContext().getTotalCount(), list));
	}
	
	@RequestMapping("/labelDel")
	@ResponseBody
	public String labelDel(String id)throws Exception{
		String[] ids = id.split(",");
		for (String c : ids) {
			labelService.deleteByPrimaryKey(c);
		}
		return JSONUtils.serialize(new Ret(0));
	}
	
	@RequestMapping(value="/labelSave",method=RequestMethod.POST)
	@ResponseBody
	public String labelSave(Label label)throws Exception{
		if(StringUtil.isEmpty(label.getId())){
			LabelExample example = new LabelExample();
			example.createCriteria().andCateCodeEqualTo(label.getCateCode()).andTitleEqualTo(label.getTitle());
			int cnt = labelService.countByExample(example);
			if(cnt > 0){
				return JSONUtils.serialize(new Ret(1,"话题已经存在"));
			}
			
			label.setCreateTime(new Date());
			label.setCreateId("-1");
			labelService.insert(label);
		}else{
			labelService.updateByPrimaryKeySelective(label);
		}
		return JSONUtils.serialize(new Ret(0));
	}
	
	@RequestMapping(value="/findLabelById")
	@ResponseBody
	public String findLabelById(String id)throws Exception{
		Label label = labelService.selectByPrimaryKey(id);
		return JSONUtils.serialize(label);
	}
	
	@RequestMapping("adList")
	@ResponseBody
	public String adList(String cateCode) {
		ForumAdExample example = new ForumAdExample();
		example.createCriteria().andCateCodeEqualTo(cateCode);
		example.setOrderByClause("sort_order desc");
		List<ForumAd> list = adService.selectByExample(example);
		return JSONUtils.serialize(list);
	}
	
	@RequestMapping(value="/findAdById")
	@ResponseBody
	public String findAdById(String id)throws Exception{
		ForumAd ad = adService.selectByPrimaryKey(id);
		return JSONUtils.serialize(ad);
	}
	
	@RequestMapping("/adDel")
	@ResponseBody
	public String adDel(String id)throws Exception{
		String[] ids = id.split(",");
		for (String c : ids) {
			adService.deleteByPrimaryKey(c);
		}
		return JSONUtils.serialize(new Ret(0));
	}
	
	@RequestMapping(value="/adSave",method=RequestMethod.POST)
	@ResponseBody
	public String adSave(ForumAd ad)throws Exception{
		if(StringUtil.isEmpty(ad.getId())){
			ad.setCreateTime(new Date());
			adService.insert(ad);
		}else{
			adService.updateByPrimaryKeySelective(ad);
		}
		return JSONUtils.serialize(new Ret(0));
	}
}
